const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 验证分类是否存在并返回分类详情
async function validateCategory(categoryCode) {
  try {
    const result = await db.collection('service_categories')
      .where({
        code: categoryCode,
        status: 'active'
      })
      .get()
    
    if (result.data.length > 0) {
      return {
        isValid: true,
        category: result.data[0]
      }
    }
    
    return {
      isValid: false,
      category: null
    }
  } catch (error) {
    console.error('验证分类失败:', error)
    return {
      isValid: false,
      category: null,
      error: error.message
    }
  }
}

// 获取所有有效分类的代码列表
async function getValidCategories() {
  try {
    const result = await db.collection('service_categories')
      .where({
        status: 'active'
      })
      .field({
        code: true,
        name: true,
        icon: true,
        color: true
      })
      .get()
    
    return {
      success: true,
      data: result.data
    }
  } catch (error) {
    console.error('获取有效分类失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

exports.main = async (event, context) => {
  const { action } = event
  
  console.log('serviceManager 云函数被调用，action:', action)
  
  try {
    switch (action) {
      case 'getServicesByCategory':
        return await getServicesByCategory(event.categoryKey)
      case 'getAllServices':
        return await getAllServices()
      case 'getServiceGrid':
        return await getServiceGrid()
      case 'getValidCategories':
        return await getValidCategories()
      case 'getServicesWithCategory':
        return await getServicesWithCategory()
      case 'getCategoryWithServices':
        return await getCategoryWithServices(event.categoryCode)
      case 'getServiceStats':
        return await getServiceStats()
      case 'searchServices':
        return await searchServices(event.keyword, event.categoryCode)
      case 'getHotServices':
        return await getHotServices(event.limit || 6)
      case 'addService':
        return await addService(event.serviceData)
      case 'updateService':
        return await updateService(event.serviceId, event.serviceData)
      case 'deleteService':
        return await deleteService(event.serviceId)
      case 'initServiceData':
        return await initServiceData(event.force || false)
      case 'updateServiceHotStatus':
        return await updateServiceHotStatus(event.serviceId, event.isHot)
      case 'batchUpdateHotStatus':
        return await batchUpdateHotStatus(event.updates)
      default:
        return {
          success: false,
          error: '未知的操作类型'
        }
    }
  } catch (error) {
    console.error('serviceManager 云函数执行失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 根据分类获取服务项
async function getServicesByCategory(categoryKey) {
  try {
    console.log('获取分类服务项:', categoryKey)
    
    const result = await db.collection('services').where({
      category: categoryKey,
      status: 'active'
    }).orderBy('sort', 'asc').get()
    
    console.log('查询结果:', result.data.length, '条记录')
    
    return {
      success: true,
      data: result.data
    }
  } catch (error) {
    console.error('获取分类服务项失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 获取所有服务项
async function getAllServices() {
  try {
    const result = await db.collection('services').where({
      status: 'active'
    }).orderBy('category', 'asc').orderBy('sort', 'asc').get()
    
    return {
      success: true,
      data: result.data
    }
  } catch (error) {
    console.error('获取所有服务项失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 获取服务网格数据（首页10个分类）
async function getServiceGrid() {
  try {
    // 获取每个分类的代表性服务（每个分类取评分最高的一个）
    const categories = [
      'sme_market', 'info_integration', 'engineering', 'network_maintenance', 
      'smart_home', 'measurement', 'materials', 'construction_team', 
      'qualification', 'case_sharing'
    ]
    
    const gridServices = []
    
    for (const category of categories) {
      const result = await db.collection('services')
        .where({
          category: category,
          status: 'active'
        })
        .orderBy('rating', 'desc')
        .limit(1)
        .get()
      
      if (result.data.length > 0) {
        const service = result.data[0]
        gridServices.push({
          id: service._id,
          key: service.category,
          name: service.title.length > 8 ? service.title.substring(0, 8) : service.title,
          icon: getCategoryIcon(service.category),
          desc: service.description.length > 20 ? 
                service.description.substring(0, 20) + '...' : 
                service.description
        })
      } else {
        // 如果没有找到该分类的服务，使用默认数据
        gridServices.push(getDefaultGridItem(category))
      }
    }
    
    return {
      success: true,
      data: gridServices
    }
  } catch (error) {
    console.error('获取服务网格失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 获取分类图标
function getCategoryIcon(category) {
  const iconMap = {
    'sme_market': '🏢',
    'info_integration': '💻',
    'engineering': '🏗️',
    'network_maintenance': '🔧',
    'smart_home': '🏠',
    'measurement': '📏',
    'materials': '📦',
    'construction_team': '👷',
    'qualification': '📋',
    'case_sharing': '📚'
  }
  return iconMap[category] || '🔧'
}

// 获取默认网格项
function getDefaultGridItem(category) {
  const defaultItems = {
    'sme_market': { id: 'default_1', key: 'sme_market', name: '中小市场', icon: '🏢', desc: '市场拓展咨询' },
    'info_integration': { id: 'default_2', key: 'info_integration', name: '信息化集成', icon: '💻', desc: 'ERP/CRM集成' },
    'engineering': { id: 'default_3', key: 'engineering', name: '工程施工', icon: '🏗️', desc: '项目施工管理' },
    'network_maintenance': { id: 'default_4', key: 'network_maintenance', name: '网络维护', icon: '🔧', desc: '7x24技术支持' },
    'smart_home': { id: 'default_5', key: 'smart_home', name: '智能家居', icon: '🏠', desc: '智能化解决方案' },
    'measurement': { id: 'default_6', key: 'measurement', name: '计量检测', icon: '📏', desc: '专业检测校准' },
    'materials': { id: 'default_7', key: 'materials', name: '材料设备', icon: '📦', desc: '优质材料供应' },
    'construction_team': { id: 'default_8', key: 'construction_team', name: '施工队伍', icon: '👷', desc: '专业施工团队' },
    'qualification': { id: 'default_9', key: 'qualification', name: '企业资质', icon: '📋', desc: '资质代办服务' },
    'case_sharing': { id: 'default_10', key: 'case_sharing', name: '案例分享', icon: '📚', desc: '成功案例展示' }
  }
  return defaultItems[category] || { id: 'default', key: category, name: '未知服务', icon: '🔧', desc: '服务描述' }
}

// 添加服务项
async function addService(serviceData) {
  try {
    // 验证分类是否存在
    if (serviceData.category) {
      const categoryExists = await validateCategory(serviceData.category)
      if (!categoryExists.isValid) {
        return {
          success: false,
          error: `分类 "${serviceData.category}" 不存在或已被删除，请选择有效的分类`
        }
      }
    }

    const result = await db.collection('services').add({
      data: {
        ...serviceData,
        createTime: new Date(),
        updateTime: new Date(),
        status: 'active'
      }
    })
    
    return {
      success: true,
      data: { _id: result._id }
    }
  } catch (error) {
    console.error('添加服务项失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 更新服务项
async function updateService(serviceId, serviceData) {
  try {
    // 如果更新了分类，验证分类是否存在
    if (serviceData.category) {
      const categoryExists = await validateCategory(serviceData.category)
      if (!categoryExists.isValid) {
        return {
          success: false,
          error: `分类 "${serviceData.category}" 不存在或已被删除，请选择有效的分类`
        }
      }
    }

    const result = await db.collection('services').doc(serviceId).update({
      data: {
        ...serviceData,
        updateTime: new Date()
      }
    })
    
    return {
      success: true,
      data: result
    }
  } catch (error) {
    console.error('更新服务项失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 删除服务项（软删除）
async function deleteService(serviceId) {
  try {
    const result = await db.collection('services').doc(serviceId).update({
      data: {
        status: 'deleted',
        updateTime: new Date()
      }
    })
    
    return {
      success: true,
      data: result
    }
  } catch (error) {
    console.error('删除服务项失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 初始化服务数据
async function initServiceData(force = false) {
  try {
    console.log('开始初始化服务数据...')
    
    // 检查是否已有数据
    const existingData = await db.collection('services').count()
    if (existingData.total > 0 && !force) {
      console.log('服务数据已存在，跳过初始化。如需强制重新初始化，请使用force参数')
      return {
        success: true,
        message: '服务数据已存在，无需初始化。如需强制重新初始化，请使用force参数',
        count: existingData.total
      }
    }
    
    // 如果是强制初始化，先清空现有数据
    if (force && existingData.total > 0) {
      console.log('强制重新初始化，先清空现有服务数据...')
      
      // 分批删除数据（避免空查询条件错误）
      let deletedCount = 0
      while (true) {
        const batch = await db.collection('services').limit(20).get()
        if (batch.data.length === 0) break
        
        for (const doc of batch.data) {
          await db.collection('services').doc(doc._id).remove()
          deletedCount++
        }
      }
      
      console.log('已删除', deletedCount, '条现有数据')
    }
    
    // 初始化服务数据 - 中小市场分类6条服务，其他分类2条服务
    const serviceData = [
      // 中小市场 (6条) - 企业网络通信服务
      {
        id: 'sme_market_001',
        category: 'sme_market',
        title: '企宽延伸',
        description: '企业专线网络延伸服务，提供高速稳定的企业级网络连接，支持多点互联和带宽弹性扩展',
        price: 2800,
        unit: '月',
        rating: 4.9,
        tags: ['企业专线', '网络延伸', '高速连接', '多点互联'],
        image: 'https://images.unsplash.com/photo-1544197150-b99a580bb7a8?w=400&h=300&fit=crop',
        badge: '热门',
        sort: 1,
        isHot: true, // 热门服务
        advantages: ['高速稳定', '专线品质', '弹性扩展', '24小时保障'],
        cases: [
          { title: '制造企业多厂区互联', image: 'https://images.unsplash.com/photo-1544197150-b99a580bb7a8?w=300' }
        ]
      },
      {
        id: 'sme_market_002',
        category: 'sme_market',
        title: '商宽延伸',
        description: '商业宽带网络延伸服务，为商业场所提供高品质互联网接入，支持多用户并发和流量管理',
        price: 1200,
        unit: '月',
        rating: 4.8,
        tags: ['商业宽带', '网络延伸', '多用户', '流量管理'],
        image: 'https://images.unsplash.com/photo-1558494949-ef010cbdcc31?w=400&h=300&fit=crop',
        badge: '推荐',
        sort: 2,
        isHot: false,
        advantages: ['高性价比', '快速部署', '流量控制', '技术支持'],
        cases: [
          { title: '连锁门店网络覆盖', image: 'https://images.unsplash.com/photo-1558494949-ef010cbdcc31?w=300' }
        ]
      },
      {
        id: 'sme_market_003',
        category: 'sme_market',
        title: '维保服务',
        description: '企业IT设备维护保养服务，包含服务器、网络设备、办公设备的定期维护和故障处理',
        price: 3500,
        unit: '月',
        rating: 4.7,
        tags: ['设备维护', '故障处理', '定期保养', '技术支持'],
        image: 'https://images.unsplash.com/photo-1581092160562-40aa08e78837?w=400&h=300&fit=crop',
        badge: '专业',
        sort: 3,
        isHot: false,
        advantages: ['专业团队', '快速响应', '预防性维护', '成本节约'],
        cases: [
          { title: '金融企业IT维保', image: 'https://images.unsplash.com/photo-1581092160562-40aa08e78837?w=300' }
        ]
      },
      {
        id: 'sme_market_004',
        category: 'sme_market',
        title: 'e企组网',
        description: '企业级组网解决方案，提供SD-WAN、VPN、局域网等组网服务，实现企业内部高效通信',
        price: 5000,
        unit: '套',
        rating: 4.9,
        tags: ['企业组网', 'SD-WAN', 'VPN', '内部通信'],
        image: 'https://images.unsplash.com/photo-1563013544-824ae1b704d3?w=400&h=300&fit=crop',
        badge: '企业级',
        sort: 4,
        isHot: true, // 热门服务
        advantages: ['安全可靠', '灵活组网', '统一管理', '扩展性强'],
        cases: [
          { title: '跨区域企业组网', image: 'https://images.unsplash.com/photo-1563013544-824ae1b704d3?w=300' }
        ]
      },
      {
        id: 'sme_market_005',
        category: 'sme_market',
        title: 'e企收银',
        description: '企业级智能收银系统，支持多种支付方式，提供会员管理、营销推广、数据分析等功能',
        price: 1500,
        unit: '套',
        rating: 4.8,
        tags: ['智能收银', '移动支付', '会员管理', '数据分析'],
        image: 'https://images.unsplash.com/photo-1556742049-0cfed4f6a45d?w=400&h=300&fit=crop',
        badge: '智能',
        sort: 5,
        isHot: false,
        advantages: ['多支付方式', '会员营销', '数据统计', '云端同步'],
        cases: [
          { title: '连锁餐饮收银系统', image: 'https://images.unsplash.com/photo-1556742049-0cfed4f6a45d?w=300' }
        ]
      },
      {
        id: 'sme_market_006',
        category: 'sme_market',
        title: '云视讯',
        description: '企业云视频会议系统，支持高清视频通话、屏幕共享、会议录制，助力企业高效沟通协作',
        price: 800,
        unit: '月',
        rating: 4.9,
        tags: ['视频会议', '云通信', '屏幕共享', '会议录制'],
        image: 'https://images.unsplash.com/photo-1542744173-8e7e53415bb0?w=400&h=300&fit=crop',
        badge: '高清',
        sort: 6,
        isHot: true, // 热门服务
        advantages: ['高清画质', '稳定连接', '多人会议', '移动办公'],
        cases: [
          { title: '远程办公视频会议', image: 'https://images.unsplash.com/photo-1542744173-8e7e53415bb0?w=300' }
        ]
      },

      // 信息化集成 (9条) - 智慧化解决方案
      {
        id: 'info_integration_001',
        category: 'info_integration',
        title: '智慧园区',
        description: '智慧园区综合管理平台，集成物业管理、安防监控、能耗管理、访客管理等功能',
        price: 150000,
        unit: '套',
        rating: 4.9,
        tags: ['智慧园区', '物业管理', '安防监控', '能耗管理'],
        image: 'https://images.unsplash.com/photo-1486406146926-c627a92ad1ab?w=400&h=300&fit=crop',
        badge: '热门',
        sort: 1,
        isHot: true, // 热门服务
        advantages: ['一体化管理', '智能化运营', '节能降耗', '安全可靠'],
        cases: [
          { title: '科技产业园智慧化改造', image: 'https://images.unsplash.com/photo-1486406146926-c627a92ad1ab?w=300' }
        ]
      },
      {
        id: 'info_integration_002',
        category: 'info_integration',
        title: '智慧社区',
        description: '智慧社区管理系统，包含门禁管理、停车管理、物业服务、邻里社交等功能',
        price: 80000,
        unit: '套',
        rating: 4.8,
        tags: ['智慧社区', '门禁管理', '停车管理', '物业服务'],
        image: 'https://images.unsplash.com/photo-1560518883-ce09059eeffa?w=400&h=300&fit=crop',
        badge: '推荐',
        sort: 2,
        isHot: false,
        advantages: ['便民服务', '安全管理', '智能化', '社区互动'],
        cases: [
          { title: '高端住宅社区智慧化', image: 'https://images.unsplash.com/photo-1560518883-ce09059eeffa?w=300' }
        ]
      },
      {
        id: 'info_integration_003',
        category: 'info_integration',
        title: '智慧教育',
        description: '智慧教育平台，提供在线教学、学生管理、成绩分析、家校互动等教育信息化服务',
        price: 120000,
        unit: '套',
        rating: 4.9,
        tags: ['智慧教育', '在线教学', '学生管理', '家校互动'],
        image: 'https://images.unsplash.com/photo-1503676260728-1c00da094a0b?w=400&h=300&fit=crop',
        badge: '专业',
        sort: 3,
        isHot: true, // 热门服务
        advantages: ['教学创新', '管理高效', '数据分析', '个性化学习'],
        cases: [
          { title: '中小学智慧校园建设', image: 'https://images.unsplash.com/photo-1503676260728-1c00da094a0b?w=300' }
        ]
      },
      {
        id: 'info_integration_004',
        category: 'info_integration',
        title: '智慧医疗',
        description: '智慧医疗信息系统，包含电子病历、预约挂号、远程诊疗、医院管理等功能',
        price: 200000,
        unit: '套',
        rating: 4.8,
        tags: ['智慧医疗', '电子病历', '远程诊疗', '医院管理'],
        image: 'https://images.unsplash.com/photo-1559757148-5c350d0d3c56?w=400&h=300&fit=crop',
        badge: '高端',
        sort: 4,
        isHot: false,
        advantages: ['诊疗高效', '数据安全', '远程服务', '智能分析'],
        cases: [
          { title: '三甲医院信息化升级', image: 'https://images.unsplash.com/photo-1559757148-5c350d0d3c56?w=300' }
        ]
      },
      {
        id: 'info_integration_005',
        category: 'info_integration',
        title: '智慧办公',
        description: '智慧办公平台，集成OA系统、会议管理、资产管理、人员考勤等办公自动化功能',
        price: 50000,
        unit: '套',
        rating: 4.7,
        tags: ['智慧办公', 'OA系统', '会议管理', '考勤管理'],
        image: 'https://images.unsplash.com/photo-1497366216548-37526070297c?w=400&h=300&fit=crop',
        badge: '实用',
        sort: 5,
        isHot: false,
        advantages: ['办公高效', '流程优化', '移动办公', '数据统计'],
        cases: [
          { title: '企业总部智慧办公', image: 'https://images.unsplash.com/photo-1497366216548-37526070297c?w=300' }
        ]
      },
      {
        id: 'info_integration_006',
        category: 'info_integration',
        title: '智慧交通',
        description: '智慧交通管理系统，包含交通监控、信号控制、车辆管理、出行服务等功能',
        price: 300000,
        unit: '套',
        rating: 4.9,
        tags: ['智慧交通', '交通监控', '信号控制', '出行服务'],
        image: 'https://images.unsplash.com/photo-1449824913935-59a10b8d2000?w=400&h=300&fit=crop',
        badge: '前沿',
        sort: 6,
        isHot: false,
        advantages: ['交通优化', '智能调度', '安全监控', '数据分析'],
        cases: [
          { title: '城市交通智能化改造', image: 'https://images.unsplash.com/photo-1449824913935-59a10b8d2000?w=300' }
        ]
      },
      {
        id: 'info_integration_007',
        category: 'info_integration',
        title: '智慧文旅',
        description: '智慧文旅平台，提供景区管理、游客服务、票务系统、文化展示等旅游信息化服务',
        price: 100000,
        unit: '套',
        rating: 4.8,
        tags: ['智慧文旅', '景区管理', '游客服务', '票务系统'],
        image: 'https://images.unsplash.com/photo-1469474968028-56623f02e42e?w=400&h=300&fit=crop',
        badge: '创新',
        sort: 7,
        isHot: false,
        advantages: ['游客体验', '运营高效', '文化传承', '数据洞察'],
        cases: [
          { title: '5A级景区智慧化建设', image: 'https://images.unsplash.com/photo-1469474968028-56623f02e42e?w=300' }
        ]
      },
      {
        id: 'info_integration_008',
        category: 'info_integration',
        title: '数字政府',
        description: '数字政府平台，提供政务服务、行政审批、公共服务、数据开放等数字化政务服务',
        price: 500000,
        unit: '套',
        rating: 4.9,
        tags: ['数字政府', '政务服务', '行政审批', '数据开放'],
        image: 'https://images.unsplash.com/photo-1454165804606-c3d57bc86b40?w=400&h=300&fit=crop',
        badge: '权威',
        sort: 8,
        isHot: true, // 热门服务
        advantages: ['服务便民', '审批高效', '数据共享', '透明公开'],
        cases: [
          { title: '区县级数字政府建设', image: 'https://images.unsplash.com/photo-1454165804606-c3d57bc86b40?w=300' }
        ]
      },
      {
        id: 'info_integration_009',
        category: 'info_integration',
        title: '数字乡村',
        description: '数字乡村建设平台，包含农业管理、村务公开、便民服务、电商平台等乡村数字化服务',
        price: 80000,
        unit: '套',
        rating: 4.7,
        tags: ['数字乡村', '农业管理', '村务公开', '便民服务'],
        image: 'https://images.unsplash.com/photo-1500382017468-9049fed747ef?w=400&h=300&fit=crop',
        badge: '惠民',
        sort: 9,
        isHot: false,
        advantages: ['乡村振兴', '农业现代化', '信息便民', '产业发展'],
        cases: [
          { title: '美丽乡村数字化建设', image: 'https://images.unsplash.com/photo-1500382017468-9049fed747ef?w=300' }
        ]
      },

      // 工程施工 (4条) - 专业工程服务
      {
        id: 'engineering_001',
        category: 'engineering',
        title: '施工承揽',
        description: '专业工程施工承揽服务，承接各类建筑、装修、机电安装等工程项目施工',
        price: 500,
        unit: '㎡',
        rating: 4.9,
        tags: ['施工承揽', '工程管理', '质量保证', '工期控制'],
        image: 'https://images.unsplash.com/photo-1541888946425-d81bb19240f5?w=400&h=300&fit=crop',
        badge: '专业',
        sort: 1,
        isHot: true, // 热门服务
        advantages: ['资质齐全', '经验丰富', '质量保证', '工期准时'],
        cases: [
          { title: '大型商业综合体施工', image: 'https://images.unsplash.com/photo-1541888946425-d81bb19240f5?w=300' }
        ]
      },
      {
        id: 'engineering_002',
        category: 'engineering',
        title: '设计勘察',
        description: '工程设计勘察服务，提供地质勘察、方案设计、施工图设计、工程咨询等专业服务',
        price: 50000,
        unit: '项',
        rating: 4.8,
        tags: ['设计勘察', '地质勘察', '方案设计', '工程咨询'],
        image: 'https://images.unsplash.com/photo-1503387762-592deb58ef4e?w=400&h=300&fit=crop',
        badge: '专业',
        sort: 2,
        isHot: false,
        advantages: ['技术权威', '经验丰富', '精准勘察', '设计优化'],
        cases: [
          { title: '大型基建项目勘察设计', image: 'https://images.unsplash.com/photo-1503387762-592deb58ef4e?w=300' }
        ]
      },
      {
        id: 'engineering_003',
        category: 'engineering',
        title: '技术支撑',
        description: '工程技术支撑服务，提供技术咨询、方案优化、技术培训、问题解决等专业技术支持',
        price: 8000,
        unit: '月',
        rating: 4.7,
        tags: ['技术支撑', '技术咨询', '方案优化', '技术培训'],
        image: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=400&h=300&fit=crop',
        badge: '技术',
        sort: 3,
        isHot: false,
        advantages: ['技术专业', '响应及时', '解决方案', '持续支持'],
        cases: [
          { title: '复杂工程技术支撑', image: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=300' }
        ]
      },
      {
        id: 'engineering_004',
        category: 'engineering',
        title: '工程监理',
        description: '专业工程监理服务，提供施工监督、质量控制、进度管理、安全监管等全程监理服务',
        price: 30000,
        unit: '项',
        rating: 4.9,
        tags: ['工程监理', '质量控制', '进度管理', '安全监管'],
        image: 'https://images.unsplash.com/photo-1504307651254-35680f356dfd?w=400&h=300&fit=crop',
        badge: '权威',
        sort: 4,
        isHot: false,
        advantages: ['监理专业', '质量保证', '风险控制', '合规管理'],
        cases: [
          { title: '重点工程项目监理', image: 'https://images.unsplash.com/photo-1504307651254-35680f356dfd?w=300' }
        ]
      },

      // 网络维护 (5条) - 专业维护服务
      {
        id: 'network_maintenance_001',
        category: 'network_maintenance',
        title: '局域网维护',
        description: '企业局域网维护服务，包含网络设备维护、网络优化、故障排除、安全防护等',
        price: 2800,
        unit: '月',
        rating: 4.8,
        tags: ['局域网维护', '网络优化', '故障排除', '安全防护'],
        image: 'https://images.unsplash.com/photo-1544197150-b99a580bb7a8?w=400&h=300&fit=crop',
        badge: '专业',
        sort: 1,
        isHot: false,
        advantages: ['专业技术', '快速响应', '预防性维护', '7x24支持'],
        cases: [
          { title: '企业总部局域网维护', image: 'https://images.unsplash.com/photo-1544197150-b99a580bb7a8?w=300' }
        ]
      },
      {
        id: 'network_maintenance_002',
        category: 'network_maintenance',
        title: '智能设备维护',
        description: '智能设备维护服务，包含物联网设备、智能终端、传感器等设备的维护保养',
        price: 3500,
        unit: '月',
        rating: 4.7,
        tags: ['智能设备', '物联网', '传感器', '终端维护'],
        image: 'https://images.unsplash.com/photo-1581092160562-40aa08e78837?w=400&h=300&fit=crop',
        badge: '智能',
        sort: 2,
        isHot: false,
        advantages: ['设备专业', '技术先进', '远程监控', '预测维护'],
        cases: [
          { title: '智慧园区设备维护', image: 'https://images.unsplash.com/photo-1581092160562-40aa08e78837?w=300' }
        ]
      },
      {
        id: 'network_maintenance_003',
        category: 'network_maintenance',
        title: '机房维护',
        description: '专业机房维护服务，包含机房环境监控、设备巡检、故障处理、安全管理等',
        price: 5000,
        unit: '月',
        rating: 4.9,
        tags: ['机房维护', '环境监控', '设备巡检', '安全管理'],
        image: 'https://images.unsplash.com/photo-1558494949-ef010cbdcc31?w=400&h=300&fit=crop',
        badge: '可靠',
        sort: 3,
        isHot: true, // 热门服务
        advantages: ['环境控制', '安全保障', '专业维护', '24小时监控'],
        cases: [
          { title: '数据中心机房维护', image: 'https://images.unsplash.com/photo-1558494949-ef010cbdcc31?w=300' }
        ]
      },
      {
        id: 'network_maintenance_004',
        category: 'network_maintenance',
        title: '数智工程维保服务',
        description: '数字化智能工程维保服务，提供智能化设备、数字化系统的专业维护保养服务',
        price: 4500,
        unit: '月',
        rating: 4.8,
        tags: ['数智工程', '智能化设备', '数字化系统', '维保服务'],
        image: 'https://images.unsplash.com/photo-1563013544-824ae1b704d3?w=400&h=300&fit=crop',
        badge: '数智',
        sort: 4,
        isHot: false,
        advantages: ['技术前沿', '智能诊断', '预测维护', '数据分析'],
        cases: [
          { title: '智慧城市数智工程维保', image: 'https://images.unsplash.com/photo-1563013544-824ae1b704d3?w=300' }
        ]
      },
      {
        id: 'network_maintenance_005',
        category: 'network_maintenance',
        title: '新能源充电桩维护',
        description: '新能源充电桩维护服务，包含充电设备检测、故障维修、性能优化、安全检查等',
        price: 3000,
        unit: '月',
        rating: 4.7,
        tags: ['充电桩维护', '新能源', '设备检测', '故障维修'],
        image: 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=400&h=300&fit=crop',
        badge: '绿色',
        sort: 5,
        isHot: false,
        advantages: ['新能源专业', '安全可靠', '快速维修', '节能环保'],
        cases: [
          { title: '城市充电站维护', image: 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=300' }
        ]
      },

      // 智能家居 (6条) - 智慧生活解决方案
      {
        id: 'smart_home_001',
        category: 'smart_home',
        title: '智能家居定制',
        description: '全屋智能家居系统定制设计，提供个性化智能生活解决方案',
        price: 25000,
        unit: '套',
        rating: 4.9,
        tags: ['智能家居定制', '个性化设计', '全屋智能', '生活便捷'],
        image: 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=400&h=300&fit=crop',
        badge: '定制',
        sort: 1,
        isHot: true, // 热门服务
        advantages: ['个性定制', '智能控制', '节能环保', '生活便捷'],
        cases: [
          { title: '豪华别墅智能家居定制', image: 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=300' }
        ]
      },
      {
        id: 'smart_home_002',
        category: 'smart_home',
        title: '全屋WiFi',
        description: '全屋WiFi覆盖解决方案，消除信号盲区，享受高速网络体验',
        price: 3000,
        unit: '套',
        rating: 4.8,
        tags: ['全屋WiFi', '信号覆盖', '高速网络', '无缝漫游'],
        image: 'https://images.unsplash.com/photo-1544197150-b99a580bb7a8?w=400&h=300&fit=crop',
        badge: '高速',
        sort: 2,
        isHot: true, // 热门服务
        advantages: ['全屋覆盖', '高速稳定', '无缝漫游', '智能管理'],
        cases: [
          { title: '大户型全屋WiFi覆盖', image: 'https://images.unsplash.com/photo-1544197150-b99a580bb7a8?w=300' }
        ]
      },
      {
        id: 'smart_home_003',
        category: 'smart_home',
        title: '智能安防',
        description: '智能安防监控系统，包含智能门锁、监控摄像、报警系统等安全防护',
        price: 8000,
        unit: '套',
        rating: 4.9,
        tags: ['智能安防', '智能门锁', '监控摄像', '报警系统'],
        image: 'https://images.unsplash.com/photo-1558002038-1055907df827?w=400&h=300&fit=crop',
        badge: '安全',
        sort: 3,
        isHot: false,
        advantages: ['智能识别', '远程监控', '及时报警', '安全可靠'],
        cases: [
          { title: '家庭智能安防系统', image: 'https://images.unsplash.com/photo-1558002038-1055907df827?w=300' }
        ]
      },
      {
        id: 'smart_home_004',
        category: 'smart_home',
        title: '可视化对讲',
        description: '智能可视化对讲系统，支持远程开门、访客识别、视频通话等功能',
        price: 2500,
        unit: '套',
        rating: 4.7,
        tags: ['可视化对讲', '远程开门', '访客识别', '视频通话'],
        image: 'https://images.unsplash.com/photo-1586996292898-71f4036c4e07?w=400&h=300&fit=crop',
        badge: '便民',
        sort: 4,
        isHot: false,
        advantages: ['可视通话', '远程控制', '访客管理', '安全便捷'],
        cases: [
          { title: '小区可视化对讲升级', image: 'https://images.unsplash.com/photo-1586996292898-71f4036c4e07?w=300' }
        ]
      },
      {
        id: 'smart_home_005',
        category: 'smart_home',
        title: '智能窗帘',
        description: '智能电动窗帘系统，支持语音控制、手机控制、定时控制等多种操作方式',
        price: 1500,
        unit: '套',
        rating: 4.6,
        tags: ['智能窗帘', '电动控制', '语音控制', '定时控制'],
        image: 'https://images.unsplash.com/photo-1586023492125-27b2c045efd7?w=400&h=300&fit=crop',
        badge: '舒适',
        sort: 5,
        isHot: false,
        advantages: ['多种控制', '静音运行', '节能遮光', '美观实用'],
        cases: [
          { title: '豪华酒店智能窗帘', image: 'https://images.unsplash.com/photo-1586023492125-27b2c045efd7?w=300' }
        ]
      },
      {
        id: 'smart_home_006',
        category: 'smart_home',
        title: '智能灯光',
        description: '智能照明控制系统，支持亮度调节、色温调节、场景模式等智能化照明体验',
        price: 2000,
        unit: '套',
        rating: 4.8,
        tags: ['智能灯光', '亮度调节', '色温调节', '场景模式'],
        image: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=400&h=300&fit=crop',
        badge: '智能',
        sort: 6,
        isHot: false,
        advantages: ['智能调节', '节能环保', '场景丰富', '氛围营造'],
        cases: [
          { title: '现代家居智能照明', image: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=300' }
        ]
      },

      // 计量检测 (7条) - 专业检测认证服务
      {
        id: 'measurement_001',
        category: 'measurement',
        title: '传输系统',
        description: '通信传输系统检测，包含光纤传输、微波传输、卫星传输等系统的性能检测',
        price: 5000,
        unit: '次',
        rating: 4.9,
        tags: ['传输系统', '光纤传输', '微波传输', '性能检测'],
        image: 'https://images.unsplash.com/photo-1544197150-b99a580bb7a8?w=400&h=300&fit=crop',
        badge: '专业',
        sort: 1,
        isHot: false,
        advantages: ['技术权威', '检测精准', '报告详细', '服务专业'],
        cases: [
          { title: '电信运营商传输系统检测', image: 'https://images.unsplash.com/photo-1544197150-b99a580bb7a8?w=300' }
        ]
      },
      {
        id: 'measurement_002',
        category: 'measurement',
        title: '交换系统',
        description: '通信交换系统检测，包含程控交换机、IP交换机、软交换等设备的功能检测',
        price: 4500,
        unit: '次',
        rating: 4.8,
        tags: ['交换系统', '程控交换', 'IP交换', '功能检测'],
        image: 'https://images.unsplash.com/photo-1558494949-ef010cbdcc31?w=400&h=300&fit=crop',
        badge: '可靠',
        sort: 2,
        isHot: false,
        advantages: ['设备专业', '检测全面', '技术先进', '质量保证'],
        cases: [
          { title: '企业交换系统检测', image: 'https://images.unsplash.com/photo-1558494949-ef010cbdcc31?w=300' }
        ]
      },
      {
        id: 'measurement_003',
        category: 'measurement',
        title: '同步系统',
        description: '通信同步系统检测，包含时钟同步、频率同步、相位同步等系统的精度检测',
        price: 3500,
        unit: '次',
        rating: 4.7,
        tags: ['同步系统', '时钟同步', '频率同步', '精度检测'],
        image: 'https://images.unsplash.com/photo-1581092160562-40aa08e78837?w=400&h=300&fit=crop',
        badge: '精准',
        sort: 3,
        isHot: false,
        advantages: ['精度高', '技术专业', '检测准确', '标准规范'],
        cases: [
          { title: '通信网络同步系统检测', image: 'https://images.unsplash.com/photo-1581092160562-40aa08e78837?w=300' }
        ]
      },
      {
        id: 'measurement_004',
        category: 'measurement',
        title: '光缆线路',
        description: '光缆线路检测，包含光缆衰耗、接头损耗、OTDR测试等光缆线路性能检测',
        price: 2000,
        unit: '次',
        rating: 4.8,
        tags: ['光缆线路', '衰耗检测', 'OTDR测试', '性能检测'],
        image: 'https://images.unsplash.com/photo-1563013544-824ae1b704d3?w=400&h=300&fit=crop',
        badge: '光纤',
        sort: 4,
        isHot: false,
        advantages: ['技术先进', '检测精确', '设备专业', '服务及时'],
        cases: [
          { title: '城域网光缆线路检测', image: 'https://images.unsplash.com/photo-1563013544-824ae1b704d3?w=300' }
        ]
      },
      {
        id: 'measurement_005',
        category: 'measurement',
        title: '电磁环境辐射检测/监测',
        description: '电磁环境辐射检测监测，包含基站辐射、电磁兼容性、环境电磁场强度等检测',
        price: 8000,
        unit: '次',
        rating: 4.9,
        tags: ['电磁辐射', '环境监测', '电磁兼容', '场强检测'],
        image: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=400&h=300&fit=crop',
        badge: '环保',
        sort: 5,
        isHot: false,
        advantages: ['权威检测', '环保合规', '数据准确', '报告详细'],
        cases: [
          { title: '5G基站电磁辐射检测', image: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=300' }
        ]
      },
      {
        id: 'measurement_006',
        category: 'measurement',
        title: '在用局用交换设备计费性能',
        description: '在用局用交换设备计费性能检测，确保计费系统准确性和设备性能稳定',
        price: 6000,
        unit: '次',
        rating: 4.8,
        tags: ['计费性能', '交换设备', '性能检测', '准确性验证'],
        image: 'https://images.unsplash.com/photo-1450101499163-c8848c66ca85?w=400&h=300&fit=crop',
        badge: '计费',
        sort: 6,
        isHot: false,
        advantages: ['计费准确', '性能稳定', '检测专业', '质量保证'],
        cases: [
          { title: '运营商计费系统检测', image: 'https://images.unsplash.com/photo-1450101499163-c8848c66ca85?w=300' }
        ]
      },
      {
        id: 'measurement_007',
        category: 'measurement',
        title: '以太网数据网系统',
        description: '以太网数据网系统检测，包含网络性能、数据传输、协议分析等全面检测',
        price: 4000,
        unit: '次',
        rating: 4.7,
        tags: ['以太网', '数据网系统', '网络性能', '协议分析'],
        image: 'https://images.unsplash.com/photo-1544197150-b99a580bb7a8?w=400&h=300&fit=crop',
        badge: '网络',
        sort: 7,
        isHot: false,
        advantages: ['网络专业', '检测全面', '分析深入', '技术先进'],
        cases: [
          { title: '企业以太网系统检测', image: 'https://images.unsplash.com/photo-1544197150-b99a580bb7a8?w=300' }
        ]
      },

      // 材料设备 (2条) - 通信材料设备供应
      {
        id: 'materials_001',
        category: 'materials',
        title: '皮线光缆',
        description: '高品质皮线光缆供应，适用于室内布线、FTTH接入等场景，质量稳定可靠',
        price: 2.5,
        unit: '米',
        rating: 4.8,
        tags: ['皮线光缆', '室内布线', 'FTTH', '光纤接入'],
        image: 'https://images.unsplash.com/photo-1563013544-824ae1b704d3?w=400&h=300&fit=crop',
        badge: '优质',
        sort: 1,
        isHot: false,
        advantages: ['质量稳定', '性能优异', '价格合理', '库存充足'],
        cases: [
          { title: '小区FTTH光缆布线', image: 'https://images.unsplash.com/photo-1563013544-824ae1b704d3?w=300' }
        ]
      },
      {
        id: 'materials_002',
        category: 'materials',
        title: '千兆穿墙王',
        description: '千兆穿墙王路由器设备，强信号覆盖，适用于大户型、别墅等复杂环境',
        price: 299,
        unit: '台',
        rating: 4.7,
        tags: ['千兆路由器', '穿墙王', '强信号', '大户型'],
        image: 'https://images.unsplash.com/photo-1544197150-b99a580bb7a8?w=400&h=300&fit=crop',
        badge: '热销',
        sort: 2,
        isHot: false,
        advantages: ['信号强劲', '覆盖广泛', '千兆速率', '稳定可靠'],
        cases: [
          { title: '别墅WiFi覆盖方案', image: 'https://images.unsplash.com/photo-1544197150-b99a580bb7a8?w=300' }
        ]
      },

      // 施工队伍
      {
        id: 'construction_team_001',
        category: 'construction_team',
        title: '专业施工队伍',
        description: '经验丰富的专业施工团队，技术过硬',
        price: 300,
        unit: '人天',
        rating: 4.8,
        tags: ['专业施工', '经验丰富', '技术过硬'],
        image: 'https://images.unsplash.com/photo-1541888946425-d81bb19240f5?w=400',
        badge: '专业',
        sort: 1,
        isHot: false,
        advantages: ['技术过硬', '经验丰富', '团队协作', '安全规范'],
        cases: [
          { title: '大型工程施工', image: 'https://images.unsplash.com/photo-1541888946425-d81bb19240f5?w=300' }
        ]
      },
      {
        id: 'construction_team_002',
        category: 'construction_team',
        title: '装修施工队',
        description: '专业装修施工队伍，工艺精湛，质量保证',
        price: 200,
        unit: '人天',
        rating: 4.7,
        tags: ['装修施工', '工艺精湛', '质量保证'],
        image: 'https://images.unsplash.com/photo-1586023492125-27b2c045efd7?w=400',
        sort: 2,
        isHot: false,
        advantages: ['工艺精湛', '质量保证', '进度保证', '售后服务'],
        cases: [
          { title: '精装修施工', image: 'https://images.unsplash.com/photo-1586023492125-27b2c045efd7?w=300' }
        ]
      },

      // 企业资质
      {
        id: 'qualification_001',
        category: 'qualification',
        title: '建筑资质代办',
        description: '建筑施工资质代办服务，专业高效',
        price: 50000,
        unit: '项',
        rating: 4.9,
        tags: ['资质代办', '建筑施工', '专业高效'],
        image: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=400',
        badge: '高效',
        sort: 1,
        isHot: false,
        advantages: ['专业团队', '经验丰富', '成功率高', '服务周到'],
        cases: [
          { title: '建筑企业资质办理', image: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=300' }
        ]
      },
      {
        id: 'qualification_002',
        category: 'qualification',
        title: '安全许可证办理',
        description: '安全生产许可证办理，合规经营保障',
        price: 30000,
        unit: '项',
        rating: 4.8,
        tags: ['安全许可证', '合规经营', '保障'],
        image: 'https://images.unsplash.com/photo-1450101499163-c8848c66ca85?w=400',
        sort: 2,
        isHot: false,
        advantages: ['合规办理', '快速审批', '专业指导', '后续维护'],
        cases: [
          { title: '企业安全许可证', image: 'https://images.unsplash.com/photo-1450101499163-c8848c66ca85?w=300' }
        ]
      },

      // 案例分享
      {
        id: 'case_sharing_001',
        category: 'case_sharing',
        title: '成功案例展示',
        description: '分享我们的成功项目案例，展示专业实力',
        price: 0,
        unit: '免费',
        rating: 4.9,
        tags: ['案例展示', '成功项目', '专业实力'],
        image: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=400',
        badge: '精选',
        sort: 1,
        isHot: false,
        advantages: ['真实案例', '经验分享', '技术展示', '客户见证'],
        cases: [
          { title: '某科技公司ERP系统集成', image: 'https://images.unsplash.com/photo-1551434678-e076c223a692?w=300' },
          { title: '智能制造工厂数字化改造', image: 'https://images.unsplash.com/photo-1541888946425-d81bb19240f5?w=300' },
          { title: '连锁酒店智能家居升级', image: 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=300' },
          { title: '政府机关网络安全维护', image: 'https://images.unsplash.com/photo-1544197150-b99a580bb7a8?w=300' },
          { title: '医院信息化系统建设', image: 'https://images.unsplash.com/photo-1581092160562-40aa08e78837?w=300' }
        ]
      },
      {
        id: 'case_sharing_002',
        category: 'case_sharing',
        title: '客户见证视频',
        description: '客户亲身见证，分享合作体验和项目效果',
        price: 0,
        unit: '免费',
        rating: 4.8,
        tags: ['客户见证', '合作体验', '项目效果'],
        image: 'https://images.unsplash.com/photo-1460925895917-afdab827c52f?w=400',
        sort: 2,
        isHot: false,
        advantages: ['真实反馈', '口碑见证', '信任建立', '服务认可'],
        cases: [
          { title: '制造企业客户见证', image: 'https://images.unsplash.com/photo-1460925895917-afdab827c52f?w=300' },
          { title: '服务业客户分享', image: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=300' }
        ]
      }
    ]
    
    // 批量插入数据
    const promises = serviceData.map(service => 
      db.collection('services').add({
        data: {
          ...service,
          createTime: new Date(),
          updateTime: new Date(),
          status: 'active'
        }
      })
    )
    
    const results = await Promise.all(promises)
    
    console.log('服务数据初始化完成，插入', results.length, '条记录')
    
    return {
      success: true,
      message: force ? '强制重新初始化服务数据完成' : '服务数据初始化完成',
      count: results.length
    }
    
  } catch (error) {
    console.error('初始化服务数据失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// ==================== 新增关联查询功能 ====================

// 获取所有服务项并关联分类信息
async function getServicesWithCategory() {
  try {
    // 获取所有有效的服务项
    const servicesResult = await db.collection('services')
      .where({
        status: 'active'
      })
      .orderBy('category', 'asc')
      .orderBy('sort', 'asc')
      .get()

    if (servicesResult.data.length === 0) {
      return {
        success: true,
        data: []
      }
    }

    // 获取所有分类信息
    const categoriesResult = await db.collection('service_categories')
      .where({
        status: 'active'
      })
      .get()

    // 创建分类查找映射
    const categoryMap = {}
    categoriesResult.data.forEach(category => {
      categoryMap[category.code] = category
    })

    // 关联服务和分类信息
    const servicesWithCategory = servicesResult.data.map(service => ({
      ...service,
      categoryInfo: categoryMap[service.category] || {
        code: service.category,
        name: '未知分类',
        icon: '❓',
        color: '#cccccc'
      }
    }))

    return {
      success: true,
      data: servicesWithCategory
    }
  } catch (error) {
    console.error('获取服务项与分类关联信息失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 获取指定分类及其所有服务项
async function getCategoryWithServices(categoryCode) {
  try {
    // 获取分类信息
    const categoryResult = await db.collection('service_categories')
      .where({
        code: categoryCode,
        status: 'active'
      })
      .get()

    if (categoryResult.data.length === 0) {
      return {
        success: false,
        error: `分类 "${categoryCode}" 不存在`
      }
    }

    const category = categoryResult.data[0]

    // 获取该分类下的所有服务项
    const servicesResult = await db.collection('services')
      .where({
        category: categoryCode,
        status: 'active'
      })
      .orderBy('sort', 'asc')
      .get()

    // 计算分类统计信息
    const totalServices = servicesResult.data.length
    const avgRating = totalServices > 0 
      ? (servicesResult.data.reduce((sum, service) => sum + (service.rating || 0), 0) / totalServices).toFixed(1)
      : 0
    
    const priceRange = totalServices > 0 ? {
      min: Math.min(...servicesResult.data.map(s => s.price || 0)),
      max: Math.max(...servicesResult.data.map(s => s.price || 0))
    } : { min: 0, max: 0 }

    return {
      success: true,
      data: {
        category: {
          ...category,
          stats: {
            totalServices,
            avgRating: parseFloat(avgRating),
            priceRange
          }
        },
        services: servicesResult.data
      }
    }
  } catch (error) {
    console.error('获取分类及服务信息失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 获取服务统计信息
async function getServiceStats() {
  try {
    // 获取总体统计
    const totalServicesResult = await db.collection('services').where({ status: 'active' }).count()
    const totalCategoriesResult = await db.collection('service_categories').where({ status: 'active' }).count()

    // 获取每个分类的服务数量
    const categoriesResult = await db.collection('service_categories')
      .where({ status: 'active' })
      .get()

    const categoryStats = []
    for (const category of categoriesResult.data) {
      const serviceCountResult = await db.collection('services')
        .where({
          category: category.code,
          status: 'active'
        })
        .count()

      // 获取该分类的平均评分
      const servicesResult = await db.collection('services')
        .where({
          category: category.code,
          status: 'active'
        })
        .get()

      const avgRating = servicesResult.data.length > 0
        ? (servicesResult.data.reduce((sum, service) => sum + (service.rating || 0), 0) / servicesResult.data.length).toFixed(1)
        : 0

      categoryStats.push({
        categoryCode: category.code,
        categoryName: category.name,
        categoryIcon: category.icon,
        serviceCount: serviceCountResult.total,
        avgRating: parseFloat(avgRating)
      })
    }

    // 获取评分最高的服务
    const topRatedResult = await db.collection('services')
      .where({ status: 'active' })
      .orderBy('rating', 'desc')
      .limit(5)
      .get()

    // 获取最新添加的服务
    const latestResult = await db.collection('services')
      .where({ status: 'active' })
      .orderBy('createTime', 'desc')
      .limit(5)
      .get()

    return {
      success: true,
      data: {
        overview: {
          totalServices: totalServicesResult.total,
          totalCategories: totalCategoriesResult.total,
          lastUpdate: new Date()
        },
        categoryStats,
        topRatedServices: topRatedResult.data,
        latestServices: latestResult.data
      }
    }
  } catch (error) {
    console.error('获取服务统计信息失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 获取热门服务（用于首页展示）
async function getHotServices(limit = 6) {
  try {
    // 首先获取标记为热门的服务
    const hotServicesResult = await db.collection('services')
      .where({ 
        status: 'active',
        isHot: true
      })
      .orderBy('rating', 'desc')
      .get()

    let filteredServices = hotServicesResult.data.slice(0, limit)

    // 如果热门服务数量不够，补充高评分且有图片的服务
    if (filteredServices.length < limit) {
      const additionalResult = await db.collection('services')
        .where({ 
          status: 'active'
        })
        .orderBy('rating', 'desc')
        .limit(limit * 2)
        .get()

      const existingIds = new Set(filteredServices.map(s => s._id))
      const additionalServices = additionalResult.data
        .filter(service => 
          !existingIds.has(service._id) && 
          service.image && 
          service.rating >= 4.5 &&
          !service.isHot // 排除已经标记为热门的
        )
        .slice(0, limit - filteredServices.length)

      filteredServices.push(...additionalServices)
    }

    // 如果还是不够，补充最新的服务
    if (filteredServices.length < limit) {
      const latestResult = await db.collection('services')
        .where({ 
          status: 'active'
        })
        .orderBy('createTime', 'desc')
        .limit(limit)
        .get()

      const existingIds = new Set(filteredServices.map(s => s._id))
      const latestServices = latestResult.data
        .filter(service => !existingIds.has(service._id))
        .slice(0, limit - filteredServices.length)

      filteredServices.push(...latestServices)
    }

    // 获取相关分类信息
    const categoryMap = {}
    if (filteredServices.length > 0) {
      const categoryCodesSet = new Set(filteredServices.map(s => s.category))
      const categoryCodes = Array.from(categoryCodesSet)
      
      for (const code of categoryCodes) {
        const categoryResult = await db.collection('service_categories')
          .where({ code, status: 'active' })
          .get()
        
        if (categoryResult.data.length > 0) {
          categoryMap[code] = categoryResult.data[0]
        }
      }
    }

    // 关联分类信息并转换为首页需要的格式
    const hotServices = filteredServices.map(service => ({
      _id: service._id,        // 保留原始的_id字段，用于serviceId关联
      id: service._id,         // 兼容性字段
      title: service.title,
      description: service.description,
      image: service.image || 'https://images.unsplash.com/photo-1551434678-e076c223a692?w=400&h=300&fit=crop',
      price: service.price || '面议',
      unit: service.unit || '',
      rating: service.rating || '4.5',
      badge: service.badge || '',
      tags: service.tags || [],
      category: service.category,
      serviceType: service.category,  // 添加serviceType字段
      categoryInfo: categoryMap[service.category] || {
        code: service.category,
        name: '未知分类',
        icon: '❓',
        color: '#cccccc'
      }
    }))

    return {
      success: true,
      data: hotServices
    }
  } catch (error) {
    console.error('获取热门服务失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 搜索服务项（支持关键词和分类过滤）
async function searchServices(keyword, categoryCode) {
  try {
    let query = db.collection('services').where({ status: 'active' })

    // 如果指定了分类，先按分类过滤
    if (categoryCode) {
      query = query.where({ category: categoryCode })
    }

    // 获取所有符合分类条件的服务
    const allServicesResult = await query.get()
    let filteredServices = allServicesResult.data

    // 如果有关键词，进行客户端过滤（因为云数据库不支持全文搜索）
    if (keyword && keyword.trim()) {
      const searchKeyword = keyword.trim().toLowerCase()
      filteredServices = allServicesResult.data.filter(service => {
        return (
          service.title.toLowerCase().includes(searchKeyword) ||
          service.description.toLowerCase().includes(searchKeyword) ||
          (service.tags && service.tags.some(tag => tag.toLowerCase().includes(searchKeyword)))
        )
      })
    }

    // 获取相关分类信息
    const categoryMap = {}
    if (filteredServices.length > 0) {
      const categoryCodesSet = new Set(filteredServices.map(s => s.category))
      const categoryCodes = Array.from(categoryCodesSet)
      
      for (const code of categoryCodes) {
        const categoryResult = await db.collection('service_categories')
          .where({ code, status: 'active' })
          .get()
        
        if (categoryResult.data.length > 0) {
          categoryMap[code] = categoryResult.data[0]
        }
      }
    }

    // 关联分类信息
    const servicesWithCategory = filteredServices.map(service => ({
      ...service,
      categoryInfo: categoryMap[service.category] || {
        code: service.category,
        name: '未知分类',
        icon: '❓',
        color: '#cccccc'
      }
    }))

    return {
      success: true,
      data: {
        services: servicesWithCategory,
        searchInfo: {
          keyword: keyword || '',
          categoryCode: categoryCode || '',
          totalResults: servicesWithCategory.length,
          searchTime: new Date()
        }
      }
    }
  } catch (error) {
    console.error('搜索服务项失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 更新服务热门状态
async function updateServiceHotStatus(serviceId, isHot) {
  try {
    const updateResult = await db.collection('services')
      .doc(serviceId)
      .update({
        isHot: isHot,
        updateTime: new Date()
      })

    if (updateResult.stats.updated === 0) {
      return {
        success: false,
        error: '服务不存在或更新失败'
      }
    }

    return {
      success: true,
      message: `服务热门状态已${isHot ? '设置为热门' : '取消热门'}`
    }
  } catch (error) {
    console.error('更新服务热门状态失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 批量更新服务热门状态
async function batchUpdateHotStatus(updates) {
  try {
    const results = []
    
    for (const update of updates) {
      const { serviceId, isHot } = update
      const result = await updateServiceHotStatus(serviceId, isHot)
      results.push({
        serviceId,
        isHot,
        ...result
      })
    }

    const successCount = results.filter(r => r.success).length
    const failCount = results.length - successCount

    return {
      success: true,
      data: {
        results,
        summary: {
          total: results.length,
          success: successCount,
          failed: failCount
        }
      }
    }
  } catch (error) {
    console.error('批量更新服务热门状态失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
} 